package com.edt.ichannel.api.service.impl;


import cc.edt.iceutils2.number.IceNumberUtils;
import cc.edt.iceutils2.random.IceRandomUtils;
import cc.edt.iceutils2.string.IceStringUtils;
import cc.edt.iceutils3.date.IceDateFormatUtils;
import cc.edt.iceutils3.json.IceFastJsonUtils;
import cc.edt.iceutils3.net.IceOkHttpUtils;
import cc.edt.iceutils3.random.IceIdGenerateUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.edt.ichannel.api.common.constant.CommonConstant;
import com.edt.ichannel.api.common.entity.ActionResult;
import com.edt.ichannel.api.entiy.local.*;
import com.edt.ichannel.api.service.*;
import com.edt.ichannel.utils.*;
import com.jcraft.jsch.SftpException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileNotFoundException;
import java.net.SocketTimeoutException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 调用接口服务
 * @author sl
 */
@Slf4j
@Service
public class EdtApiServiceImpl implements EdtApiService {

    private static final String SOCKET_TIME_EXCEPTION_READ_TIME_OUT = "READ TIMED OUT";
    private static final String PAY_RESULT_TYPE_SUCCESS = "1";
    private static final String PAY_RESULT_TYPE_SOLVING = "0";
    private static final String SING_TYPE_RSA_SHA256 = "RSA_SHA256";

    private static final String UNICOMPAY_BATCH_FILE_SUBFIX = ".REQ";


    @Resource
    private InterfaceLogService logService;
    @Resource
    private InterfaceLogService interfaceLogService;
    @Resource
    private WoaccountService woaccountService;

    @Resource
    private FirstmoneyLogService firstmoneyLogService;

    @Resource
    private UnicomPayReqService unicomPayReqService;




    @Override
    public ActionResult sanHu(String phone, String infoList) {
        ActionResult result = new ActionResult();
        log.info("sanHu入参:" + "phone:"+phone+"infoList :"+infoList);
        Map<String, String> map = new HashMap<>();
        map.put("user", CommonConstant.USER_EDTAPI);
        map.put("pwd", CommonConstant.PWD_EDTAPI);
        map.put("number", phone);
        map.put("infoList", infoList);
        try {
            result = JSON.parseObject(IceOkHttpUtils.doHttpPost(CommonConstant.URL_SANHU, map, 10000), ActionResult.class);
            log.info("sanHu返回结果：" + IceFastJsonUtils.toJsonString(result));
        } catch (Exception e) {
            log.info("sanHu异常：" + e.getMessage());
            result.setMessage("sanHu异常：" + e.getMessage());
            result.setSuccess(false);
        } finally {
            logService.addLog(result, IceFastJsonUtils.toJsonString(map), CommonConstant.URL_SANHU, CommonConstant.INTERFACE_TYPE_SNAHU);
        }

        return result;
    }

    @Override
    public ActionResult trafficCbss(EdtApiParamEntity params) {
        ActionResult result = new ActionResult();
        log.info("trafficCbss入参:" + IceFastJsonUtils.toJsonString(params));
        String json = getTrafficJson(params);
        try {
            log.info("----------------aop traffic json:" + json);
            result = JSON.parseObject(IceOkHttpUtils.doHttpPost(CommonConstant.URL_TRAFFIC, json, 15000), ActionResult.class);
            log.info("trafficCbss返回结果：" + IceFastJsonUtils.toJsonString(result));
        } catch (Exception e) {
            log.info("trafficCbss异常：" + e.getMessage());
            result.setMessage("trafficCbss异常：" + e.getMessage());
            result.setSuccess(false);
        } finally {
            logService.addLog(result, json, CommonConstant.URL_TRAFFIC, CommonConstant.INTERFACE_TYPE_TRAFFIC_CBSS);
        }

        return result;
    }

    private String getTrafficJson(EdtApiParamEntity params) {
        return "{\n" +
                "    \"user\": \"" + CommonConstant.USER_EDTAPI + "\",\n" +
                "    \"pwd\": \"" + CommonConstant.PWD_EDTAPI + "\",\n" +
                "    \"phone\": \"" + params.getPhone() + "\",\n" +
                "    \"productInfo\": [{\n" +
                "        \"enableTag\": \"" + params.getEnableTag() + "\",\n" +
                "        \"optType\": \"" + params.getOptType() + "\",\n" +
                "        \"packageElement\": [{\n" +
                "            \"elementId\": \"" + params.getElementId() + "\",\n" +
                "            \"packageId\": \"" + params.getPackageId() + "\",\n" +
                "            \"elementType\":\"D\"\n" +
                "        }],\n" +
                "        \"productId\": \"" + params.getProductId() + "\"\n" +
                "    }]\n" +
                "}";
    }

    @Override
    public ActionResult trafficEss(EdtApiParamEntity params) {
        ActionResult result = new ActionResult();
        Map<String, String> map = new HashMap<>();
        map.put("user", CommonConstant.USER_EDTAPI);
        map.put("pwd", CommonConstant.PWD_EDTAPI);
        map.put("phone", params.getPhone());
        map.put("serviceID", params.getServiceId());
        String enableTag = CommonConstant.ENABLE_TAG_EFFECT_NEXT_MONTH.equals(params.getEnableTag()) ? CommonConstant.ENABLE_TAG_EFFECT_NEXT_MONTH_ESS : CommonConstant.ENABLE_TAG_EFFECT_NOW_ESS;
        map.put("enableTag", enableTag);
        String optType = CommonConstant.OPT_TAG_ORDER.equals(params.getOptType()) ? CommonConstant.OPT_TAG_ORDER_ESS : CommonConstant.OPT_TAG_UNSUBSCRIBE_ESS;
        map.put("optType", optType);
        try {
            log.info("trafficEss入参:" + IceFastJsonUtils.toJsonString(map));
            result = JSON.parseObject(IceOkHttpUtils.doHttpPost(CommonConstant.URL_TRAFFIC_ESS, map, 15000), ActionResult.class);
            log.info("trafficEss返回结果：" + IceFastJsonUtils.toJsonString(result));
        } catch (Exception e) {
            log.info("trafficEss异常：" + e.getMessage());
            result.setMessage("trafficEss异常：" + e.getMessage());
            result.setSuccess(false);
        } finally {
            map.put("pwd", "");
            logService.addLog(result, IceFastJsonUtils.toJsonString(map), CommonConstant.URL_TRAFFIC_ESS, CommonConstant.INTERFACE_TYPE_TRAFFIC_ESS);
        }
        return result;
    }

    @Override
    public String getAccessToken(String appId) {
        String accesstoken = "";
        Map<String, String> map = new HashMap<>();
        map.put("user", CommonConstant.USER_EDTAPI);
        map.put("pwd", CommonConstant.PWD_EDTAPI);
        map.put("appId", appId);
        ActionResult actionResult = new ActionResult();
        try {
            String s = IceOkHttpUtils.doHttpPost(CommonConstant.URL_GETACCESSTOKEN, map, 30000);
            log.info("getAccessToken：" + s);
            actionResult = JSON.parseObject(s, ActionResult.class);
            if (actionResult.isSuccess()) {
                if (actionResult.getResultList() != null) {
                    JSONObject jsonObj = (JSONObject) actionResult.getResultList();
                    accesstoken = jsonObj.getString(CommonConstant.KEY_ACCESSTOKEN);
                } else {
                    return null;
                }
            } else {
                return null;
            }
        } catch (Exception e) {
            log.info("getAccessToken error：" + e.getMessage());
            actionResult.setMessage("getAccessToken error：" + e.getMessage());
            actionResult.setSuccess(false);
        } finally {
            map.put("pwd", "");
            logService.addLog(actionResult, IceFastJsonUtils.toJsonString(map), CommonConstant.URL_GETACCESSTOKEN, CommonConstant.INTERFACE_TYPE_GETACCESSTOKEN);
        }

        return accesstoken;
    }

    @Override
    public ActionResult woPay(HttpPostParamsWoPay woPayParams) {
        ActionResult actionResult = new ActionResult();
        String url = CommonConstant.URL_SINGLEISSUESERVLET;
        Woaccount woaccount = woaccountService.getWoaccountByMerNo(woPayParams.getMerNo());
        log.info("沃支付--商户信息====" + JSON.toJSONString(woaccount));
        if (woaccount != null) {
            String merCer = CommonConstant.CONFIG_WO_CERPATH + woaccount.getMerNo() + ".pfx";
            File file = new File(merCer);
            if (file.exists()) {
                String cerPinCode = woaccount.getMerPincode();
                String callbackcer = CommonConstant.CONFIG_WO_CALLBACKCER;
                log.info("沃支付--商户证书文件====" + merCer);
                log.info("沃支付--商户证书密码====" + cerPinCode);
                log.info("沃支付--商户回调地址====" + callbackcer);

                SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
                SimpleDateFormat sf2 = new SimpleDateFormat("yyyyMMddHHmmss");

                //	SecureRandom random = new SecureRandom();
                //	String randomNum = String.valueOf(random.nextInt());
                String reqTime = sf2.format(new Date());
                String orderDate = sf.format(new Date());
                //String orderNo = System.currentTimeMillis() + "" + randomNum.substring(randomNum.length() - 3);
                String interfaceVersion = "1.0.0.1";
                String tranType = "DF01";
                String signType = "RSA_SHA256";
                String woType = "3";
                String bizCode = "017";
                String reqIp = "127.0.0.1";
                String callbackUrl = "http://m.hlj165.com/ichannel_api/pay/callBack";
                String amount = String.valueOf(Integer.parseInt(woPayParams.getAmount()) - Integer.parseInt(woPayParams.getFee()));

                Map<String, String> params = new HashMap<>();
                params.put("interfaceVersion", interfaceVersion);
                params.put("tranType", tranType);
                params.put("merNo", woPayParams.getMerNo());//平台商商户号
                params.put("orderDate", orderDate);
                params.put("reqTime", reqTime);
                params.put("orderNo", woPayParams.getOrderNo());
                params.put("amount", amount);//付款金额（分）
                params.put("bizCode", bizCode);
                params.put("payeeAcc", woPayParams.getPayeeAcc());//收款人沃帐户
                params.put("payeeName", "");//收款人姓名
                params.put("payeeBankCode", "");
                params.put("payeeBankBranch", "");
                params.put("callbackUrl", callbackUrl);
                params.put("reqIp", reqIp);
                params.put("merExtend", "");
                params.put("signType", signType);
                params.put("woType", woType);

                //证书签名
                String signMsg = UniPaySignUtils.merSign(params, signType, merCer, cerPinCode);
                params.put("signMsg", signMsg);
                if (signMsg == null) {
                    signMsg = "";
                }
                params.put("signMsg", signMsg);
                log.info("沃支付--支付请求参数====" + JSON.toJSONString(params));


                try {
                    String result = HttpClientUtil.URLPost(url, "UTF-8", "UTF-8", params);
                    Map mapResult = null;
                    log.info("沃支付--支付响应信息====" + result);

                    if (!IceStringUtils.isBlank(result)) {
                        mapResult = new StrUtils().stringSplit(result);
                        Map<String, String> paramMap = UniPaySignUtils.rep2Map(result);
                        boolean rasule1 = false;
                        if (SING_TYPE_RSA_SHA256.equals(mapResult.get("signType"))) {
                            rasule1 = UniPaySignUtils.merVerify(paramMap, mapResult.get("signType").toString(), mapResult.get("signMsg").toString(), callbackcer);
                        } else {
                            signMsg = SignUtil.getMd5SignMsg(paramMap, ConfigInfo.SingleIssueKey, "UTF-8");
                            rasule1 = signMsg.endsWith(mapResult.get("signMsg").toString());
//                            if (signMsg.endsWith(mapResult.get("signMsg").toString())) {
//                                rasule1 = true;
//                            } else {
//                                rasule1 = false;
//                            }
                        }
//                        boolean payresult = "1".equals(mapResult.get("transRst").toString()) ? true : false;
                        boolean payresult = PAY_RESULT_TYPE_SUCCESS.equals(mapResult.get("transRst").toString()) || PAY_RESULT_TYPE_SOLVING.equals(mapResult.get("transRst").toString()) ;
                        actionResult.setSuccess(payresult);
                        actionResult.setMessage(mapResult.get("transDis").toString());
                        actionResult.setResultList(paramMap);
                    } else {
                        actionResult.setSuccess(false);
                        actionResult.setMessage("代发系统未返回结果！");
                    }
                }catch (SocketTimeoutException e1){
                    log.error("------------------------支付接口异常:"+ e1.getMessage());
                    e1.printStackTrace();
                    if(IceStringUtils.isNotBlank(e1.getMessage()) && IceStringUtils.contains(e1.getMessage().toUpperCase(),SOCKET_TIME_EXCEPTION_READ_TIME_OUT)){
                        actionResult.setSuccess(true);
                        actionResult.setMessage("支付接口异常：" + e1.getMessage()+"按照成功处理");
                    }else{
                        actionResult.setSuccess(false);
                        actionResult.setMessage("支付接口异常：" + e1.getMessage());
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("------------------------支付接口异常:"+e.getMessage());
                    actionResult.setSuccess(false);
                    actionResult.setMessage("支付接口异常：" + e.getMessage());
                }



                interfaceLogService.addLog(actionResult, JSON.toJSONString(params), url, CommonConstant.INTERFACE_TYPE_WOPAY);

            } else {
                actionResult.setSuccess(false);
                actionResult.setMessage("商户证书文件不存在！");
                interfaceLogService.addLog(actionResult, merCer, url, CommonConstant.INTERFACE_TYPE_WOPAY);
            }
        } else {
            actionResult.setSuccess(false);
            actionResult.setMessage("未配置沃帐户信息，无法支付");
            interfaceLogService.addLog(actionResult,"未配置沃帐户信息，无法支付" , url, CommonConstant.INTERFACE_TYPE_WOPAY);
        }
        return actionResult;
    }

    @Override
    public String getCityCodeByCode(String cityCode) {
        ActionResult result = getCityByCode(cityCode);
        if (result.isSuccess()) {
            if (result.getResultList() != null) {
                JSONObject jsonObj = (JSONObject) result.getResultList();
                return jsonObj.getString(CommonConstant.KEY_CITYCODE);
            } else {
                return null;
            }
        }
        return null;
    }

    @Override
    public ActionResult getCityByCode(String cityCode) {
        ActionResult result = new ActionResult();
        Map<String, String> map = new HashMap<>();
        map.put("user", CommonConstant.USER_EDTAPI);
        map.put("pwd", CommonConstant.PWD_EDTAPI);
        map.put("cityCode", cityCode);
        try {
            log.info("getCityByCode入参:" + IceFastJsonUtils.toJsonString(map));
            result = JSON.parseObject(IceOkHttpUtils.doHttpPost(CommonConstant.URL_GET_CITY, map, 10000), ActionResult.class);
            log.info("getCityByCode返回结果：" + IceFastJsonUtils.toJsonString(result));
        } catch (Exception e) {
            log.info("getCityByCode异常：" + e.getMessage());
            result.setMessage("getCityByCode异常：" + e.getMessage());
            result.setSuccess(false);
        }
        map.put("pwd", "");
        logService.addLog(result, IceFastJsonUtils.toJsonString(map), CommonConstant.URL_TRAFFIC_ESS, CommonConstant.INTERFACE_TYPE_TRAFFIC_ESS);
        return result;
    }

    @Override
    public ActionResult sendsms(SendSMS sendSMS) {
        return smsSendMessage(sendSMS.getReceivePhone(), sendSMS.getContent());
    }

    @Override
    public ActionResult selectFirstMoneyInfo(String serviceCode, String orderCode, Date orderDate) {
        ActionResult result = new ActionResult();
        EntityForKafka requestParam = new EntityForKafka();
        EntityForKafkaUniBssInfo uniBssInfo = new EntityForKafkaUniBssInfo();
        uniBssInfo.setSERIAL_NUMBER(serviceCode);
        uniBssInfo.setTRANS_IDO(orderCode);
        uniBssInfo.setORDER_TIME(orderDate);
        requestParam.setUNI_BSS_INFO(uniBssInfo);
        requestParam.setUser(CommonConstant.USER_EDTAPI);
        requestParam.setPwd(CommonConstant.PWD_EDTAPI);
        String json = IceFastJsonUtils.toJsonStringNoNull(requestParam, "yyyyMMddHHmm");
        try {
            log.info("selectFirstMoneyInfo:" + json);
            String returnStr = IceOkHttpUtils.doHttpPost(CommonConstant.URL_SELECT_FIRST_MONEY, json, 5000);
            log.info("selectFirstMoneyInfo：" + returnStr);
            result  = JSON.parseObject(returnStr,ActionResult.class);
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage("selectFirstMoneyInfo：" + e.getMessage());
            result.setSuccess(false);
        } finally {
            logService.addLog(result, json, CommonConstant.URL_SELECT_FIRST_MONEY, CommonConstant.INTERFACE_TYPE_SELECT_FIRST_MONEY);
        }

        return result;
    }

    @Override
    public ActionResult smsSendMessage(String phone, String text) {
        Map<String, String> map = new HashMap<>();
        map.put("user", CommonConstant.USER_EDTAPI);
        map.put("pwd", CommonConstant.PWD_EDTAPI);
        map.put("telNumber", phone);
        map.put("content", text);
        ActionResult result = new ActionResult();
        try {
            String returnStr = IceOkHttpUtils.doHttpPost(CommonConstant.URL_SENDSMS10010, map, 30000);
            result = JSON.parseObject(returnStr, ActionResult.class);
        } catch (Exception e) {
            result.setMessage("sendSms10010 exception：" + e.getMessage());
            result.setSuccess(false);
        } finally {
            map.put("pwd", "");
            logService.addLog(result, IceFastJsonUtils.toJsonString(map), CommonConstant.URL_SENDSMS10010, CommonConstant.INTERFACE_TYPE_SENDSMS10010);
        }

        return result;
    }

    @Override
    public ActionResult unicomPay(EntityFormUnicomPayParam entityFormUnicomPayParam) {
        ActionResult result = new ActionResult();

        String json = getUnicomPayJson(entityFormUnicomPayParam);
        log.info("联通支付请求报文：\n"+json);
        log.info("联通支付请求地址：\n"+CommonConstant.URL_UNICOMPAY);
        try {
            String returnStr = IceOkHttpUtils.doHttpPost(CommonConstant.URL_UNICOMPAY, json, 30000);
            log.info("联通支付返回结果："+returnStr);
            result.setMessage(returnStr);
            EntityForUnicomPayResult unicomPayResult = JSON.parseObject(returnStr,EntityForUnicomPayResult.class);
            if(CommonConstant.CODE_UNICOM_SUCCESS.equals(unicomPayResult.getCode())){
                result.setSuccess(CommonConstant.ACTIONRESULT_TRUE);
            }else{
                result.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(true);
            result.setMessage("调用联通支付或者解析出现异常,按照成功处理：" + e.getMessage());

        } finally {
            logService.addLog(result, json, CommonConstant.URL_UNICOMPAY, CommonConstant.INTERFACE_TYPE_URL_UNICOMPAY);
        }
        return result;

    }

    @Override
    public ActionResult unicomPayBatch(List<EntityForUnicomPayParamBatch> unicomPayParamBatcheList, int totalMoney) {
        ActionResult result = new ActionResult();
        if(unicomPayParamBatcheList == null){
            result.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
            result.setMessage("传入集合为空");
            return result;
        }
        if(unicomPayParamBatcheList.size() == 0){
            result.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
            result.setMessage("传入集合为空");
            return result;
        }
        if(totalMoney == 0){
            result.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
            result.setMessage("总金额为0");
            return result;
        }
        log.info("------------");
        SFTPUtil sftp = new SFTPUtil(CommonConstant.UNICOMPAY_SFTP_USERNAME, CommonConstant.UNICOMPAY_SFTP_PASSWORD,
                CommonConstant.UNICOMPAY_SFTP_HOST, CommonConstant.UNICOMPAY_SFTP_PORT);
        try {
            sftp.login();
            String batchCode = RandomUtil.ramdomOrderNo();
            String fileName = batchCode+UNICOMPAY_BATCH_FILE_SUBFIX;
            String content = getUnicomPayBatchFileContent(unicomPayParamBatcheList, batchCode,fileName,totalMoney);
            log.info("upLoadUnicomPayBatchFile content "+content);
            FileUtil.write(fileName, content, CommonConstant.UNICOMPAY_BATCH_SFTP_TEMP_PATH);
            String tempFile = CommonConstant.UNICOMPAY_BATCH_SFTP_TEMP_PATH + "/" + fileName;
            sftp.upload(CommonConstant.UNICOMPAY_SFTP_UPLOAD_PATH, tempFile);
            log.info("------------upLoadUnicomPayBatchFile");
            result = noticeUnicomPayBatch(batchCode,fileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            result.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
            result.setMessage(e.getMessage());
            log.error("文件生成失败");
            throw new RuntimeException(e);
        } catch (SftpException e) {
            e.printStackTrace();
            result.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
            result.setMessage(e.getMessage());
            log.error("文件上传失败");
            throw new RuntimeException(e);
        } finally {
            sftp.logout();
        }
        logService.addLog(result, "调用无支付批量", "调用无支付批量", CommonConstant.INTERFACE_TYPE_SYNALLEXPANSION);
        return result;
    }

    private String getUnicomPayBatchFileContent(List<EntityForUnicomPayParamBatch> unicomPayParamBatcheList, String batchCode, String fileName, int totalMoney){
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(CommonConstant.TX_UNICOMPAY).append(CommonConstant.SPLIT_CHAR_SG).
                append(batchCode).append(CommonConstant.SPLIT_CHAR_SG).
                append(unicomPayParamBatcheList.size()).append(CommonConstant.SPLIT_CHAR_SG).
                append(totalMoney).append(CommonConstant.SPLIT_CHAR_SG).append("\n");
        if (!unicomPayParamBatcheList.isEmpty()) {
            int ronum = 1;
            for (EntityForUnicomPayParamBatch unicomPayParamBatch : unicomPayParamBatcheList) {
                stringBuilder.append(ronum).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(unicomPayParamBatch.getTridIdCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(CommonConstant.ROLEID_UNICOMPAY).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(unicomPayParamBatch.getWoAccount(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(unicomPayParamBatch.getName(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(unicomPayParamBatch.getMoney(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(unicomPayParamBatch.getMdlxCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(unicomPayParamBatch.getMdlxName(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(unicomPayParamBatch.getFzywNumber(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(unicomPayParamBatch.getFzspCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(unicomPayParamBatch.getFzspName(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(unicomPayParamBatch.getYwfzDate(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(unicomPayParamBatch.getFzCityCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(unicomPayParamBatch.getFzExpansionCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append(IceStringUtils.blankToDefault(unicomPayParamBatch.getFzStaffCode(), "")).append(CommonConstant.SPLIT_CHAR_SG);
                stringBuilder.append("\n");
                ronum++;
            }
        }
        return stringBuilder.toString();

    }
    @Override
    public ActionResult noticeUnicomPayBatch(String batchCode, String fileName) {
        Map<String,String> map = new HashMap<String ,String>(12);
        map.put("charset", "utf-8");
        map.put("tx", CommonConstant.TX_UNICOMPAY);
        map.put("province_code", "97");
        map.put("requestNo", IceIdGenerateUtils.toSerialCode(32));
        map.put("batno",batchCode);
        map.put("batchFile",fileName);
//        map.put("remark",entityFormUnicomPayParam.getName());
//        map.put("bankNo",entityFormUnicomPayParam.getPhone());
        map.put("signType", "md5");
        String sign = SignMsgUtil.getSignMsg(map, CommonConstant.MD5_KEY_UNICOMPAY);
        map.put("signMsg", sign);
        ActionResult result = new ActionResult();
        String json = IceFastJsonUtils.toJsonString(map);
        log.info("联通支付请求报文：\n"+json);
        log.info("联通支付请求地址：\n"+CommonConstant.URL_UNICOMPAY_BATCH);
        try {
            String returnStr = IceOkHttpUtils.doHttpPost(CommonConstant.URL_UNICOMPAY_BATCH, json, 30000);
            log.info("联通支付返回结果："+returnStr);
            result.setResultList(returnStr);
            EntityForUnicomPayResult unicomPayResult = JSON.parseObject(returnStr,EntityForUnicomPayResult.class);
            if(CommonConstant.CODE_UNICOM_SUCCESS.equals(unicomPayResult.getCode())){
                result.setSuccess(CommonConstant.ACTIONRESULT_TRUE);
            }else{
                result.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
                result.setMessage("返回CODE "+unicomPayResult.getCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage("调用联通支付或者解析出现异常：" + e.getMessage());
            result.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
        } finally {
            logService.addLog(result, json, CommonConstant.URL_UNICOMPAY_BATCH, CommonConstant.INTERFACE_TYPE_URL_UNICOMPAY_BATCH);
        }
        return result;
    }



    @Override
    public void callBackIchannel(List<UnicomPayReq> unicomPayReqs) {
        if(unicomPayReqs != null && unicomPayReqs.size() > 0){
            int count = 1;
            while(unicomPayReqs.size()  > 0 && count < 5){
                log.info("------------待回调数据数量："+unicomPayReqs.size());
                Iterator<UnicomPayReq> it = unicomPayReqs.iterator();
                while (it.hasNext()){
                    UnicomPayReq u = it.next();
                    if(callBack(u)){
                        unicomPayReqService.updateToCallBackSuccess(u.getId());
                        it.remove();
                    }
                }
                if(unicomPayReqs.size() > 0){
                    try {
                        Thread.sleep(count*30000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                count++;
            }
            if(unicomPayReqs.size() > 0){
                for (UnicomPayReq unicomPayReq :
                        unicomPayReqs) {
                    unicomPayReqService.updateToCallBackFail(unicomPayReq.getId());
                }
            }
        }

    }

    @Override
    public ActionResult getRhKdByNumberTel(String orderCode, String phoneNum) {
        Map<String,String> map = new HashMap<>(2);
        map.put("orderCode", orderCode);
        map.put("numberTel", phoneNum);
        ActionResult result = new ActionResult();
        try {
            String returnStr = IceOkHttpUtils.doHttpPost(CommonConstant.URL_GETRHKDBYNUMBERTEL, map, 30000);
            log.info("getRhKdByNumberTel："+returnStr);
            result = JSON.parseObject(returnStr,ActionResult.class);
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage("getRhKdByNumberTel：" + e.getMessage());
            result.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
        } finally {
            logService.addLog(result, IceFastJsonUtils.toJsonString(map), CommonConstant.URL_GETRHKDBYNUMBERTEL, CommonConstant.INTERFACE_TYPE_GETRHKDBYNUMBERTEL);
        }
        return result;
    }

    @Override
    public ActionResult getAreaStandardCodeLikeCityName(String cityName) {
        Map<String,String> map = new HashMap<>(3);
        map.put("user", CommonConstant.USER_EDTAPI);
        map.put("pwd", CommonConstant.PWD_EDTAPI);
        map.put("cityName", cityName);
        ActionResult result = new ActionResult();
        try {
            String returnStr = IceOkHttpUtils.doHttpPost(CommonConstant.URL_GETCITYCODEBYNAME, map, 30000);
            log.info("getAreaStandardCodeLikeCityName："+returnStr);
            result = JSON.parseObject(returnStr,ActionResult.class);
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage("getAreaStandardCodeLikeCityName：" + e.getMessage());
            result.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
        } finally {
            logService.addLog(result, IceFastJsonUtils.toJsonString(map), CommonConstant.URL_GETRHKDBYNUMBERTEL, CommonConstant.INTERFACE_TYPE_GETCITYCODEBYNAME);
        }
        return result;
    }

    @Override
    public String getCityCodeByName(String cityName) {
        if(IceStringUtils.isNotBlank(cityName)){
            if(cityName.contains("市")){
                cityName = cityName.substring(0,cityName.indexOf("市"));
            }
            ActionResult result = getCityByCode(cityName);
            if(result.isSuccess()){
                JSONObject obj = (JSONObject) result.getResultList();
                return obj.getString("cityCode");
            }
        }
        return null;
    }

    @Override
    public ActionResult developMenterSync(EntityForDevelopMenterSyncReq entityForDevelopMenterSyncReq) {
        ActionResult result = new ActionResult();
        EntityForDevelopMenterSync entityForDevelopMenterSync = new EntityForDevelopMenterSync();
        EntityForUniBssHead entityForUniBssHead = new EntityForUniBssHead();
        entityForUniBssHead.setAPP_ID(CommonConstant.APPID_DEVELOPMENTERSYNC);
        Date date = new Date();
        entityForUniBssHead.setTIMESTAMP(IceDateFormatUtils.dateToString(date,"yyyy-MM-dd HH:mm:ss SSS"));
        entityForUniBssHead.setTRANS_ID(IceDateFormatUtils.dateToString(date,"yyyyMMddHHmmssSSS")+IceRandomUtils.randomNumeric(6));
        Map<String ,String> params = new HashMap<>();
        params.put("APP_ID",entityForUniBssHead.getAPP_ID());
        params.put("TIMESTAMP",entityForUniBssHead.getTIMESTAMP());
        params.put("TRANS_ID",entityForUniBssHead.getTRANS_ID());
        String token = SignMsgUtil.getToken(params,CommonConstant.SECRET_DEVELOPMENTERSYNC);
        log.info("---------"+token);
        entityForUniBssHead.setTOKEN(token);
        entityForDevelopMenterSyncReq.setBUSI_TYPE("1");
        entityForDevelopMenterSyncReq.setDATA_SOURCE(CommonConstant.APPID_DEVELOPMENTERSYNC);
        entityForDevelopMenterSyncReq.setDEV_TYPE_ID("1".equals(entityForDevelopMenterSyncReq.getDEV_TYPE_ID()) ? "01":"02");
        EntityForDevelopMenterSyncBody entityForDevelopMenterSyncBody = new EntityForDevelopMenterSyncBody();
        entityForDevelopMenterSyncBody.setDEVELOPMENTER_SYNC_REQ(entityForDevelopMenterSyncReq);
        entityForDevelopMenterSync.setUNI_BSS_HEAD(entityForUniBssHead);
        entityForDevelopMenterSync.setUNI_BSS_BODY(entityForDevelopMenterSyncBody);
        try {
            log.info("发送地址："+CommonConstant.URL_DEVELOPMENTERSYNC);
            log.info("发送报文:"+IceFastJsonUtils.toJsonStringNoNull(entityForDevelopMenterSync));
            String returnJson = HttpPostUtil.doPostJson(CommonConstant.URL_DEVELOPMENTERSYNC, IceFastJsonUtils.toJsonStringNoNull(entityForDevelopMenterSync), "utf-8",30000);
            log.info("返回报文："+returnJson);
            result = transDevelopMenterSyncResult(returnJson);
        }catch (Exception e){
            e.printStackTrace();
            result.setMessage(e.getMessage());
            result.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
        }finally {
            logService.addLog(result, IceFastJsonUtils.toJsonStringNoNull(entityForDevelopMenterSync), CommonConstant.URL_DEVELOPMENTERSYNC, CommonConstant.INTERFACE_TYPE_JZQD);
        }

        return result;
    }

    @Override
    public ActionResult developMenterSyncRegist(EntityForDevelopMenterSyncReq entityForDevelopMenterSyncReq) {
        entityForDevelopMenterSyncReq.setOPER_TYPE("01");
        return developMenterSync(entityForDevelopMenterSyncReq);
    }

    @Override
    public ActionResult developMenterSyncUpdate(EntityForDevelopMenterSyncReq entityForDevelopMenterSyncReq) {
        entityForDevelopMenterSyncReq.setOPER_TYPE("02");
        return developMenterSync(entityForDevelopMenterSyncReq);
    }

    @Override
    public ActionResult developMenterSyncCancel(EntityForDevelopMenterSyncReq entityForDevelopMenterSyncReq) {
        entityForDevelopMenterSyncReq.setOPER_TYPE("03");
        return developMenterSync(entityForDevelopMenterSyncReq);
    }

    private ActionResult transDevelopMenterSyncResult(String returnJson){
        ActionResult result = new ActionResult();
        result.setResultList(returnJson);
        if(IceStringUtils.isNotBlank(returnJson)){
            EntityForDevelopMenterSyncResult entity = JSONObject.parseObject(returnJson,EntityForDevelopMenterSyncResult.class);
            if(entity != null && entity.getUNI_BSS_BODY() != null && entity.getUNI_BSS_BODY().getDEVELOPMENTER_SYNC_RSP() != null
                    && "01".equals(entity.getUNI_BSS_BODY().getDEVELOPMENTER_SYNC_RSP().getRETURN_STATE())){
                result.setSuccess(CommonConstant.ACTIONRESULT_TRUE);
                result.setMessage("调用成功");
                return result;
            }else{
                result.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
                result.setMessage("接口返回失败");
            }
        }
        result.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
        result.setMessage("返回报文解析失败");
        return  result;
    }
    private boolean callBack(UnicomPayReq unicomPayReq){
        try {
            String returnStr = IceOkHttpUtils.doHttpPost(CommonConstant.URL_UNICOMPAY_CALLBACK_ICHANNEL, IceFastJsonUtils.toJsonString(unicomPayReq), 30000);
            log.info("回调ichannel 返回结果："+returnStr);
            if(IceStringUtils.isNotBlank(returnStr)){
                ActionResult result = JSON.parseObject(returnStr,ActionResult.class);
                return result.isSuccess();
            }else{
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("回调 ichannel 失败:"+unicomPayReq.getPayTradId());
            return false;
        } finally {

        }
    }

    private String getUnicomPayJson(EntityFormUnicomPayParam entityFormUnicomPayParam){
        Map<String ,Map> root = new HashMap<String, Map>(1);
        Map<String ,Map> uniBssBody = new HashMap<String, Map>(1);
        Map<String,String> map = new HashMap<String ,String>(12);

        map.put("TX", CommonConstant.TX_UNICOMPAY);
        map.put("PAY_TRADE_ID",entityFormUnicomPayParam.getPayTradId());
        map.put("PHONE_NO",entityFormUnicomPayParam.getPhone());
        map.put("MONEY",entityFormUnicomPayParam.getMoney());
        map.put("ROLE_ID",CommonConstant.ROLEID_UNICOMPAY);
        String sign = SignMsgUtil.getSignMsg(map, CommonConstant.MD5_KEY_UNICOMPAY);
        map.put("SIGN_MSG", sign);

        map.put("CHARSET", "utf-8");
        map.put("PROVINCE_CODE", "97");
        map.put("SIGN_TYPE", "MD5");
        map.put("NAME",entityFormUnicomPayParam.getName());
        map.put("CITY_CODE",entityFormUnicomPayParam.getCityCode());
        Map<String,Object> paramMap = new HashMap<>(12);

        Map<String ,List> detail = new HashMap<>(1);
        Map<String,String> incentiveDetail = new HashMap<>(3);
        incentiveDetail.put("TRADE_ID",entityFormUnicomPayParam.getTradId() == null ? "" : entityFormUnicomPayParam.getTradId());
        incentiveDetail.put("INCENTIVE_NAME",entityFormUnicomPayParam.getIncentiveName() == null ? "" : repalceUrlEncode(entityFormUnicomPayParam.getIncentiveName()));
        incentiveDetail.put("INCENTIVE_MONEY",entityFormUnicomPayParam.getIncentiveMoney() == null ? "" : entityFormUnicomPayParam.getIncentiveMoney());
        List<Map<String,String>> list1 = new ArrayList<>(1);
        list1.add(incentiveDetail);
        detail.put("INCENTIVE_DETAIL",list1);
        paramMap.put("DETAIL",detail);
        paramMap.putAll(map);
        uniBssBody.put("INCENTIVE_PAY_REQ",paramMap);
        root.put("UNI_BSS_BODY",uniBssBody);
        return IceFastJsonUtils.toJsonString(root);
    }

    private String repalceUrlEncode(String str){
        String returnStr = str;
        if(str.contains("%")){
            returnStr = returnStr.replaceAll("%","%25");
        }
        if(str.contains(" ")){
            returnStr = returnStr.replaceAll(" ","%20");
        }
        if(str.contains("\"")){
            returnStr = returnStr.replaceAll("\"","%22");
        }
        if(str.contains("#")){
            returnStr = returnStr.replaceAll("#","%23");
        }
        if(str.contains("&")){
            returnStr = returnStr.replaceAll("&","%26");
        }
        if(str.contains("(")){
            returnStr = returnStr.replaceAll("\\(","%28");
        }
        if(str.contains(")")){
            returnStr = returnStr.replaceAll("\\)","%29");
        }
        if(str.contains("+")){
            returnStr = returnStr.replaceAll("\\+","%2B");
        }
        if(str.contains(",")){
            returnStr = returnStr.replaceAll(",","%2C");
        }
        if(str.contains("/")){
            returnStr = returnStr.replaceAll("/","%2F");
        }
        if(str.contains(":")){
            returnStr = returnStr.replaceAll(":","%3A");
        }
        if(str.contains(";")){
            returnStr = returnStr.replaceAll(";","%3B");
        }
        if(str.contains("<")){
            returnStr = returnStr.replaceAll("<","%3C");
        }
        if(str.contains("=")){
            returnStr = returnStr.replaceAll("=","%3D");
        }if(str.contains(">")){
            returnStr = returnStr.replaceAll(">","%3E");
        }
        if(str.contains("?")){
            returnStr = returnStr.replaceAll("\\?","%3F");
        }
        if(str.contains("@")){
            returnStr = returnStr.replaceAll("@","%40");
        }
        if(str.contains("\\")){
            returnStr = returnStr.replaceAll("\\\\","%5C");
        }

        if(str.contains("|")){
            returnStr = returnStr.replaceAll("\\|","%7C");
        }
        return returnStr;
    }
    @Override
    public ActionResult selectRelation(String serviceCode, String orderCode) {
        ActionResult result = new ActionResult();
        EntityForKafka requestParam = new EntityForKafka();
        EntityForKafkaUniBssInfo uniBssInfo = new EntityForKafkaUniBssInfo();
        uniBssInfo.setSERIAL_NUMBER(serviceCode);
        uniBssInfo.setTRANS_IDO(orderCode);
        requestParam.setUNI_BSS_INFO(uniBssInfo);
        requestParam.setUser(CommonConstant.USER_EDTAPI);
        requestParam.setPwd(CommonConstant.PWD_EDTAPI);
        String json = IceFastJsonUtils.toJsonStringNoNull(requestParam,"yyyyMMddHHmm");
        try {
            log.info("selectRelation:" + json);
            String returnStr = IceOkHttpUtils.doHttpPost(CommonConstant.URL_SELECT_RELATION,json,5000);
            log.info("selectRelation：" + returnStr);
            result  = JSON.parseObject(returnStr,ActionResult.class);
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage("selectRelation：" + e.getMessage());
            result.setSuccess(false);
        }finally {
            logService.addLog(result,json, CommonConstant.URL_SELECT_FIRST_MONEY, CommonConstant.INTERFACE_TYPE_SELECT_FIRST_MONEY);
        }
        return result;
    }

    @Override
    @Transactional
    public FirstmoneyLog selectInterfaceA(OrderChannel orderChannel) {
        //调接口
        ActionResult result = selectFirstMoneyInfo(orderChannel.getServiceCode(),orderChannel.getOrderCode(),orderChannel.getOrderDate());
        FirstmoneyLog firstmoneyLog = firstmoneyLogService.selectNewest(orderChannel.getOrderCode(),orderChannel.getServiceCode(),orderChannel.getCityCode());
        String monthStr  = IceDateFormatUtils.dateToString(new Date(),"yyyyMM");
        EntityForKafkaUniBssInfo uniBssInfo = null;
        //解析返回信息
//        if(result.isSuccess()){
//
//        }
        if(result.getResultList() != null){
            EntityForKafka returnInfo = JSON.parseObject((String)result.getResultList() ,EntityForKafka.class);
            if(returnInfo != null && returnInfo.getUNI_BSS_INFO() != null ){
                uniBssInfo = returnInfo.getUNI_BSS_INFO();
            }
        }
        firstmoneyLog = insertOrUpdateFirstMoneyLog(firstmoneyLog,orderChannel,monthStr,uniBssInfo);
        log.info("中控返回："+IceFastJsonUtils.toJsonString(result));
        log.info("解析结果："+IceFastJsonUtils.toJsonString(firstmoneyLog));
        return firstmoneyLog;
    }

    @Override
    public String selectUserId(String serviceCode, String orderCode, Date orderDate) {
        //调接口
        ActionResult result = selectFirstMoneyInfo(serviceCode,orderCode,orderDate);
        EntityForKafkaUniBssInfo uniBssInfo = null;
        if(result.getResultList() != null){
            EntityForKafka returnInfo = JSON.parseObject((String)result.getResultList() ,EntityForKafka.class);
            if(returnInfo != null && returnInfo.getUNI_BSS_INFO() != null ){
                uniBssInfo = returnInfo.getUNI_BSS_INFO();
                return uniBssInfo.getUSER_ID();
            }
        }
        log.info("中控返回："+IceFastJsonUtils.toJsonString(result));
        return null;
    }

    @Override
    public ActionResult validateUserId(String orderCode, String serviceCode, Date orderDate, String userId, String userIdKfk) {
        ActionResult result = new ActionResult();
        if(IceStringUtils.isBlank(userIdKfk)){
            //调接口
            result = selectFirstMoneyInfo(serviceCode,orderCode,orderDate);
            log.info("中控返回："+IceFastJsonUtils.toJsonString(result));
            if(result.getResultList() != null){
                EntityForKafka returnInfo = JSON.parseObject((String)result.getResultList() ,EntityForKafka.class);
                if(returnInfo != null && returnInfo.getUNI_BSS_INFO() != null ){
                    userIdKfk = returnInfo.getUNI_BSS_INFO().getUSER_ID();
                }
            }
        }
        if(userIdKfk.equals(userId)){
            result.setSuccess(CommonConstant.ACTIONRESULT_TRUE);
        }else{
            result.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
            result.setMessage("userid 发生改变 原："+userId+"新："+userIdKfk);
        }
        return result;
    }

    @Override
    public ActionResult validateDevCode(String orderCode, String serviceCode, Date orderDate, String developStaffId, String developStaffIdKfk) {
        ActionResult result = new ActionResult();
        if(IceStringUtils.isBlank(developStaffIdKfk)){
            //调接口
            result = selectFirstMoneyInfo(serviceCode,orderCode,orderDate);
            log.info("中控返回："+IceFastJsonUtils.toJsonString(result));
            if(result.getResultList() != null){
                EntityForKafka returnInfo = JSON.parseObject((String)result.getResultList() ,EntityForKafka.class);
                if(returnInfo != null && returnInfo.getUNI_BSS_INFO() != null ){
                    developStaffIdKfk = returnInfo.getUNI_BSS_INFO().getDEVELOP_STAFF_ID();
                }
            }
        }
        if(developStaffIdKfk.equals(developStaffId)){
            result.setSuccess(CommonConstant.ACTIONRESULT_TRUE);
        }else{
            result.setSuccess(CommonConstant.ACTIONRESULT_FAIL);
            result.setMessage("userid 发生改变 原："+developStaffId+"新："+developStaffIdKfk);
        }
        return result;
    }

    @Override
    @Transactional
    //验证在线状态
    public int validateOnlineState(String serviceCode, String orderCode, Date orderDate, String removeTag , String userStateCodeset) {
        if(IceStringUtils.isAnyBlank(removeTag,userStateCodeset)){
            //调接口
            ActionResult result = selectFirstMoneyInfo(serviceCode,orderCode,orderDate);
            log.info("中控返回："+IceFastJsonUtils.toJsonString(result));
            if(result.getResultList() != null){
                EntityForKafka returnInfo = JSON.parseObject((String)result.getResultList() ,EntityForKafka.class);
                if(returnInfo != null && returnInfo.getUNI_BSS_INFO() != null ){
                    removeTag = returnInfo.getUNI_BSS_INFO().getREMOVE_TAG();
                    userStateCodeset = returnInfo.getUNI_BSS_INFO().getUSER_STATE_CODESET();
                }
            }
        }
        if(IceStringUtils.isNoneBlank(removeTag,userStateCodeset)){
            if(!CommonConstant.REMOVE_TAGE_SUCCESS.equals(removeTag)){
                return CommonConstant.KFK_VALIDATE_RESULT_XH;
            }else{
                if(CommonConstant.USER_STATE_CODESET_SUCCESS.equals(userStateCodeset)){
                    return CommonConstant.KFK_VALIDATE_RESULT_ZC;
                }else {
                    return CommonConstant.KFK_VALIDATE_RESULT_QF;
                }
            }
        }
        return CommonConstant.KFK_VALIDATE_RESULT_WZ;
    }

    private FirstmoneyLog  insertOrUpdateFirstMoneyLog(FirstmoneyLog firstmoneyLog, OrderChannel orderChannel, String monthStr, EntityForKafkaUniBssInfo uniBssInfo){
        if(firstmoneyLog == null){
            firstmoneyLog = setNewFirstMoneyLog(orderChannel,monthStr,uniBssInfo);
            if(uniBssInfo != null && IceStringUtils.isNotBlank(uniBssInfo.getRSP_CODE())){
                firstmoneyLogService.inserFirstMoneyLog(firstmoneyLog);
            }

        }else{
            setOldFirstMoneyLog(firstmoneyLog,uniBssInfo);
            if(uniBssInfo != null && IceStringUtils.isNotBlank(uniBssInfo.getRSP_CODE())){
                if(monthStr.equals(firstmoneyLog.getMonthstr())){
                    firstmoneyLogService.updateFirstMoneyLog(firstmoneyLog);
                }else{
                    firstmoneyLog.setMonthstr(monthStr);
                    firstmoneyLog.setId(IceIdGenerateUtils.toSerialCode(32));
                    firstmoneyLogService.inserFirstMoneyLog(firstmoneyLog);
                }
            }

        }
        return firstmoneyLog;
    }
    private FirstmoneyLog setNewFirstMoneyLog(OrderChannel orderChannel, String monthStr, EntityForKafkaUniBssInfo uniBssInfo){
        //更新首充日志表
        FirstmoneyLog firstmoneyLog = new FirstmoneyLog();
        BeanUtils.copyProperties(orderChannel,firstmoneyLog,"id");
        firstmoneyLog.setId(IceIdGenerateUtils.toSerialCode(32));
        firstmoneyLog.setMonthstr(monthStr);
        firstmoneyLog.setUpdateDate(new Date());
        if(uniBssInfo != null){
            //有这两个属性是这件设计只存这俩，其他没有存，现在需要存入其他字段，先冗余，有时间优化
            firstmoneyLog.setFirstMoney(IceNumberUtils.toInt(uniBssInfo.getRECV_FEE(),0));
            firstmoneyLog.setFirstDate(IceStringUtils.isBlank(uniBssInfo.getRECV_TIME())  ? null : IceDateFormatUtils.stringToDate(uniBssInfo.getRECV_TIME(),"yyyy-MM-dd HH:mm:ss"));
            firstmoneyLog.setUniBssInfo(uniBssInfo);
            if(IceStringUtils.isNotBlank(uniBssInfo.getUSER_ID())){
                firstmoneyLog.setUserId(uniBssInfo.getUSER_ID());
                firstmoneyLog.setUserIdDate(new Date());
            }
        }
        return firstmoneyLog;
    }

    private void setOldFirstMoneyLog(FirstmoneyLog firstmoneyLog,EntityForKafkaUniBssInfo uniBssInfo){
        if(uniBssInfo != null){
            firstmoneyLog.setFirstMoney(IceNumberUtils.toInt(uniBssInfo.getRECV_FEE(),0));
            firstmoneyLog.setFirstDate(IceStringUtils.isBlank(uniBssInfo.getRECV_TIME())  ? null : IceDateFormatUtils.stringToDate(uniBssInfo.getRECV_TIME(),"yyyy-MM-dd HH:mm:ss"));
            firstmoneyLog.setUniBssInfo(uniBssInfo);
            firstmoneyLog.setUpdateDate(new Date());
            if(!uniBssInfo.getUSER_ID().equals(firstmoneyLog.getUserId())){
                if(IceStringUtils.isBlank(firstmoneyLog.getUserId())){
                    firstmoneyLog.setUserId(uniBssInfo.getUSER_ID());
                    firstmoneyLog.setUserIdDate(new Date());
                }else{
                    firstmoneyLog.setDifUserId(uniBssInfo.getUSER_ID());
                    firstmoneyLog.setDifUserIdDate(new Date());
                }
            }
        }
    }

    @Override
    public void selectInterfaceB(OrderCreditKd orderCreditKd) {
        //调接口
        ActionResult result = selectRelation(orderCreditKd.getServiceCode(),orderCreditKd.getOrderCode());
        String recCode = null;
        String phoneNum = null;
        String userId = null;
        //解析返回信息
        if(result.isSuccess()){
            if(result.getResultList() != null){
                List<EntityForKafkaQuerRelation> list = JSON.parseArray((String)result.getResultList(),EntityForKafkaQuerRelation.class);
                if(list != null && list.size() > 0){
                    for (EntityForKafkaQuerRelation relation :
                            list) {
                        if(relation.getUNI_BSS_INFO() != null && relation.getUNI_BSS_INFO().getRSP_CODE() != null){
                            recCode = relation.getUNI_BSS_INFO().getRSP_CODE();
                            continue;
                        }
                        if(CommonConstant.NET_TYPE_CODE_YW.equals(relation.getNET_TYPE_CODE())){
                            phoneNum = relation.getSERIAL_NUMBER_B();
                            userId = relation.getUSER_ID_A();
                        }
                    }
                }
            }
            if(CommonConstant.RSP_CODE_SUCCESS.equals(recCode) && IceStringUtils.isNotBlank(phoneNum)){
                orderCreditKd.setPhoneNumber(phoneNum);
                orderCreditKd.setUserId(userId);
            }else{
                log.info("查询失败，查询结果："+result.getResultList());
            }
        }else{
            log.info("查询失败，查询结果："+result.getResultList());

        }
    }


}
